// pages/buy/buy.js
var app = getApp();
Page({
  data: {
    hidden: true,
    offer: 0,
    items: [
      { name: '1', value: '货到付款', checked: 'true' },
      { name: '2', value: '在线支付' },
    ],
    hasCarts: false,
    noCarts: true,
  },
  radioChange: function (e) {//储存支付方式
    wx.setStorageSync('payWay', e.detail.value)
    // console.log(e.detail.value)
  },
  onLoad: function (options) {
    var that = this
    wx.getSystemInfo({//获取滑块的高宽
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });
    
    if (options.type == 1) {
      this.setData({
        groupOrder: true,
        superName: wx.getStorageSync('groupSuperName')
      })
    } else {
      var that = this;
      // console.log(wx.getStorageSync('addressID'))
      console.log(wx.getStorageSync("isaddnewaddress"))
      if (wx.getStorageSync("isaddnewaddress") == 11) {
        that.setData({//如果服务器也没有地址就让地址栏隐藏
          addressHidden: true
        })
      } else {
        if (wx.getStorageSync('haddressID')){
          wx.request({
            url: app.globalData.allUrl + "/YMGW/addressAction/getAddressOne",
            data: {
              addID: wx.getStorageSync('haddressID')
            },
            method: 'GET',
            success: function (res) {
              if (res.data.id) {//如果服务器上有地址就把服务器上的地址储存在本地    
                wx.setStorageSync('addInputUser', res.data.consignee)
                wx.setStorageSync('addInputAddress', res.data.expressageAdd)
                wx.setStorageSync('addInputPhone', res.data.phone)
                wx.setStorageSync('addressID', res.data.id)
                wx.setStorageSync('addSuperID', res.data.superId)
                wx.setStorageSync('addLocationAdd', res.data.locationAdd)
                // console.log(res.data[res.data.length - 1])
                that.setData({//如果有地址，则显示在页面上
                  inputAddress: res.data.locationAdd + res.data.expressageAdd,
                  inputPhone: res.data.phone,
                  inputUser: res.data.consignee,
                });
            }
            }
          });
        }else if (!wx.getStorageSync('addressID')) {//如果本地储存的地址没有，就从服务器上获取以前的地址
          wx.request({
            url: app.globalData.allUrl + "/YMGW/addressAction/getAddressByUserAndSuperID",
            data: {
              userID: wx.getStorageSync('userid'),
              superID: wx.getStorageSync('superID')
            },
            method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            // header: {}, // 设置请求的 header
            success: function (res) {
              //console.log(res.data)

              if (res.data.id) {//如果服务器上有地址就把服务器上的地址储存在本地    
                wx.setStorageSync('addInputUser', res.data.consignee)
                wx.setStorageSync('addInputAddress', res.data.expressageAdd)
                wx.setStorageSync('addInputPhone', res.data.phone)
                wx.setStorageSync('addressID', res.data.id)
                wx.setStorageSync('addSuperID', res.data.superId)
                wx.setStorageSync('addLocationAdd', res.data.locationAdd)
                // console.log(res.data[res.data.length - 1])
                that.setData({//如果有地址，则显示在页面上
                  inputAddress: res.data.locationAdd + res.data.expressageAdd,
                  inputPhone: res.data.phone,
                  inputUser: res.data.consignee,
                })
              } else {
                that.setData({//如果服务器也没有地址就让地址栏隐藏
                  addressHidden: true
                })
              }


            }
          })
        } else {
          if(wx.getStorageSync('addSuperID')==-1){
            that.setData({//如果本地没有超市地址就让地址栏隐藏
              addressHidden: true
            })
          }else{
            that.setData({//如果有地址，则从本地获取地址
              inputAddress: wx.getStorageSync('addLocationAdd') + wx.getStorageSync('addInputAddress'),
              inputPhone: wx.getStorageSync('addInputPhone'),
              inputUser: wx.getStorageSync('addInputUser'),
            })
          }

          
        }
      }
      // wx.setStorageSync('payWay', 1);//设置支付方式，默认为1（货到付款）
      wx.getStorage({//获取超市的名字，显示在商品列表
        //获取数据的key
        key: 'superName',
        success: function (res) {
          // console.log(res)
          that.setData({
            superName: res.data,
          })
        }
      })
      var id = getApp().requestDetailid
    }


    // console.log(that.data.superName)
  },
  onReady: function () {
    // 页面渲染完成
    getSuperPayWay(this)
  },
  onShow: function () {
    // 页面显示
    var that = this;
    // console.log( wx.getStorageSync('cartLists'))
    var cartLists = wx.getStorageSync('cartLists');//从本地缓存获取购物车的商品信息
    if (cartLists == "" || isNaN(cartLists[0].totalPrices)) {//判断购物车是否有东西，没有就显示没有，有就显示有的|
      this.setData({
        hasCarts: true,
        noCarts: false
      })
    } else {//如果购物车有物品就遍历他，在把价格算出来
      for (var y in cartLists) {//遍历购物车
        cartLists[y].totalPrices = parseFloat(cartLists[y].unitPrice * cartLists[y].quantity).toFixed(2)//让购物车里的单价乘以数量，得到单件商品的总价
      }
      this.setData({ cartLists: cartLists });//同步显示到页面
      wx.setStorageSync('cartLists', cartLists)//同步储存在本地以备购买时调用
      var totalMoneyArr = [];
      for (var index in this.data.cartLists) {//计算总的价格
        totalMoneyArr.push(parseFloat(this.data.cartLists[index].quantity * this.data.cartLists[index].unitPrice).toFixed(2));
      }
      var totalMoney = totalMoneyArr.reduce(function (a, b) {
        return (parseFloat(a) + parseFloat(b)).toFixed(2);
      });
      if (totalMoney >= 38) {//总价大于38无配送费
        this.setData({
          isFree: 0,
          totalMoney: totalMoney,
          ordertotalMoney: totalMoney
        })
      } else {
        this.setData({
          isFree: wx.getStorageSync('superShipping'),
          totalMoney: (parseFloat(totalMoney) + parseInt(wx.getStorageSync('superShipping'))).toFixed(2),
          ordertotalMoney: totalMoney
        })
      }
      wx.setStorageSync('totalMoney', that.data.totalMoney)//储存在本地以备购买时调用
      wx.setStorageSync('isFreeSendfee', this.data.isFree)
    }
    if(wx.getStorageSync('addSuperID')>-1){
      that.setData({//如果服务器也没有地址就让地址栏隐藏
        addressHidden: false,
        inputAddress: wx.getStorageSync('addLocationAdd') + wx.getStorageSync('addInputAddress'),
        inputPhone: wx.getStorageSync('addInputPhone'),
        inputUser: wx.getStorageSync('addInputUser'),
      })
    }
    show_hidden(this);
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
    //  console.log( wx.getStorageSync('cartLists'))
  },
  confirm: function () {//点击确认进入填写地址页面
    var that = this;
    that.setData({
      hidden: true
    })
    wx.navigateTo({
      url: '/pages/addAddress/addAddress',
    })
  },
  cancel: function () {//点击取消则不进入写地址页面
    var that = this;
    that.setData({
      hidden: true
    })
  },

  addQuantity: function (e) {//增加单个商品数量
    this.changeCartItemQuantity('+', e);
    show_hidden(this);
  },

  minusQuantity: function (e) {//减少单个商品数量
    this.changeCartItemQuantity('-', e);
    show_hidden(this);
  },

  changeCartItemQuantity: function (op, e) {//改变单个商品数量
    var that = this;
    var cartLists = this.data.cartLists//找到储存在本地购物车的商品信息
    var cart = cartLists.filter(function (ele) {//过滤出点击加减的商品在本地储存的唯一商品ID
      return ele.productId === e.currentTarget.dataset.id

    })[0]
    if (op === '-' && cart.quantity > 1) {//如果符号为－，则商品数量减一
      cart.quantity -= 1;
      cart.totalPrices = parseFloat(cart.quantity * cart.unitPrice).toFixed(2)
    } else if (op === '+') {//如果符号为+，则商品数量加一
      if (cart.quantity == cart.repertory) {//如果增加的数量大于库存，则取消增加；
        wx.showToast({
          title: "库存不足",
          icon: "loading"
        })
      } else {
        cart.quantity += 1;
      }
      cart.totalPrices = parseFloat(cart.quantity * cart.unitPrice).toFixed(2)
    } else if (op === '-' && cart.quantity == 1) {
      cart.quantity -= 1;
      cart.totalPrices = parseFloat(cart.quantity * cart.unitPrice).toFixed(2);
      //  console.log(cart);
    }
    for (var quantity in cartLists) {
      if (cartLists[quantity].quantity == 0) {
        cartLists.splice(quantity, 1)
      }
    }
    this.setData({ cartLists: cartLists })//同时将所修改的数量保存到当前页面的购物车中
    //  console.log(cartLists)
    wx.setStorageSync('cartLists', cartLists);
    // console.log( wx.getStorageSync('cartLists'))
    if (cartLists != "") {//当购物车不为空的时候，在计算总金额
      var totalMoneyArr = [];
      for (var index in this.data.cartLists) {
        totalMoneyArr.push(parseFloat(this.data.cartLists[index].quantity * this.data.cartLists[index].unitPrice).toFixed(2));
      }
      var totalMoney = totalMoneyArr.reduce(function (a, b) {
        return (parseFloat(a) + parseFloat(b)).toFixed(2);
      });
      if (totalMoney >= 38) {
        this.setData({
          isFree: 0,
          totalMoney: totalMoney,
          ordertotalMoney: totalMoney
        })
      } else {
        this.setData({
          isFree: wx.getStorageSync('superShipping'),
          totalMoney: (parseFloat(totalMoney) + parseInt(wx.getStorageSync('superShipping'))).toFixed(2),
          ordertotalMoney: totalMoney
        })
      }
      wx.setStorageSync('isFreeSendfee', this.data.isFree)
      // app.cartTotalMoney = totalMoney;
      // wx.setStorage({key:"cartTotalMoney",data:that.data.totalMoney})
      wx.setStorage({
        key: 'totalMoney',
        data: that.data.totalMoney
      })//同步储存到购物车
      // console.log(cartLists)
    } else {
      wx.setStorageSync('cartLists', "");
      that.setData({
        hasCarts: true,
        noCarts: false
      })
    }
  }

  ,
  getCartInfo: function () {//将用户购买的商品以及用户信息发送到后台(在线支付)    
    var that = this;
    var config = false;
    if (wx.getStorageSync('addressID') && wx.getStorageSync('addSuperID')!=-1) {
      //  console.log(wx.getStorageSync('payWay'))
      if (wx.getStorageSync('payWay') == 1) {
        // console.log(121)
        sendOrderListDetail(that, wx.getStorageSync('addInputAddress'), wx.getStorageSync('addInputPhone'), wx.getStorageSync('addInputUser'), wx.getStorageSync('addressID'), wx.getStorageSync('addSuperID'))
      } else if (wx.getStorageSync('payWay') == 2) {
        var reallyTotalMoney = parseFloat(that.data.totalMoney).toFixed(2)
        if (reallyTotalMoney >= wx.getStorageSync('upSendMoney')) {
          wx.request({
            url: app.globalData.allUrl + "/YMGW/weChatPayAction/weixinPaySuper",
            data: {
              userID: wx.getStorageSync('userid'),
              superId: wx.getStorageSync('superID'),
              detailsjson: wx.getStorageSync('cartLists'),
              addressID: wx.getStorageSync('addressID'),
              shipping_fee: parseInt(that.data.isFree),
              totalMoney: reallyTotalMoney,
              paymentType: wx.getStorageSync('payWay')
            },
            method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            // header: {}, // 设置请求的 header
            success: function (res) {             
              // success
              //  console.log(res.data)
              if (res.data == "251") {
                wx.showToast({
                  title: '库存不足',
                  icon: 'loading',
                  duration: 2000
                })
              } else if (res.data.packages) {
                var pay = res.data;
                wx.requestPayment({//如果从后台获取支付信息成功。则调用微信支付接口
                  timeStamp: pay.timeStamp,
                  nonceStr: pay.nonceStr,
                  package: pay.packages,
                  signType: pay.signType,
                  paySign: pay.paySign,
                  success: function (res) {
                    // success
                    // console.log(res)
                    wx.showToast({
                      title: '微信支付成功',
                      icon: 'success',
                      duration: 2000
                    })
                    setTimeout(function () {//两秒后跳转到我的页面
                      wx.switchTab({
                        url: '../my/my',
                        success: function (res) {
                          // success
                        }
                      })
                    }, 2000)
                  }, fail(res) {
                    wx.showToast({
                      title: '取消支付',
                      icon: 'loading',
                      duration: 2000
                    })
                  }
                })

              }
            }
          })
        } else {
          wx.showToast({
            title: '您购买的商品低于起送价',
            icon: 'loading',
            duration: 2000
          })
        }

      }
    } else if (!app.inputUser) {
      that.setData({
        hidden: false
      })
    }
  },
})





function sendOrderListDetail(that, address, phone, user, id, addSuperID) {//发送订单详情到后台
  // console.log(wx.getStorageSync('superID') +"==="+addSuperID)
  if (wx.getStorageSync('superID') == addSuperID || addSuperID == -1) {
    var reallyTotalMoney = parseFloat(that.data.totalMoney).toFixed(2)
    if (reallyTotalMoney >= wx.getStorageSync('upSendMoney')) {
      // console.log(reallyTotalMoney)
      wx.request({//将用户的订单信息发送到后台
        url: app.globalData.allUrl + "/YMGW/orderFormAction/shoppingToSuperMarket",
        method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        data: {
          userID: wx.getStorageSync('userid'),
          superID: wx.getStorageSync('superID'),
          detailsjson: wx.getStorageSync('cartLists'),
          addressID: wx.getStorageSync('addressID'),
          shipping_fee: parseInt(that.data.isFree),
          totalMoney: reallyTotalMoney,
          paymentType: wx.getStorageSync('payWay')
        },
        success: function (res) {
          //console.log(res)
          if (res.data == true) {
            wx.showToast({
              title: '提交订单成功',
              icon: 'success',
              duration: 2000
            });
            wx.setStorageSync('cartLists', "")//购买成功后清空购物车
            setTimeout(function () {//两秒后跳转到我的页面
              wx.switchTab({
                url: '../my/my',
                success: function (res) {
                  // success
                }
              })
            }, 2000)
          }
          else if (res.data == false) {
            wx.showToast({
              title: '提交订单失败',
              icon: 'loading',
              duration: 2000
            })
          } else if (res.data == 251) {
            wx.showToast({
              title: '库存不足',
              icon: 'loading',
              duration: 2000
            })
          }
        }, fail: function () {
          wx.showToast({
            title: '该商品已过期，请删除后重新购买',
            icon: 'loading',
            duration: 2000
          })
        }
      })
    } else {
      wx.showToast({
        title: '您购买的商品低于起送价',
        icon: 'loading',
        duration: 2000
      })
    }
  }

}


function getSuperPayWay(that) {//获取超市的支付方式
  wx.request({
    url: app.globalData.allUrl + "/YMGW/superMarketAction/getSuperPayment_mode",
    data: {
      superId: wx.getStorageSync('superID')
    },
    method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    // header: {}, // 设置请求的 header
    success: function (res) {
      // success
      //   console.log(res.data)
      if (res.data == 1) {
        wx.setStorageSync('payWay', 1)
        that.setData({
          items: [
            { name: '1', value: '货到付款', checked: 'true' },
          ],
        })
      } else if (res.data == 2) {
        wx.setStorageSync('payWay', 2)
        that.setData({
          items: [
            { name: '2', value: '在线支付', checked: 'true' },
          ],

        })
      } else if (res.data == 0) {
        wx.setStorageSync('payWay', 1)
        that.setData({
          items: [
            { name: '1', value: '货到付款', checked: 'true' },
            { name: '2', value: '在线支付', },
          ],

        })
      }
    }
  })
}
function show_hidden(that) {
   var reallyTotalMoney = parseFloat(that.data.totalMoney).toFixed(2);
   if (reallyTotalMoney < wx.getStorageSync('upSendMoney')) {
      that.setData({
         show_sendprice: "起送价",
         sendprice: wx.getStorageSync('upSendMoney'),
         istrue: false,
         isfalse: true

      });

   } else {
      that.setData({
         istrue: true,
         isfalse: false
      })
   }
}




